<template>
  <div id="item-zx" style="width: 500px; height: 285px;"></div>
</template>

<script>
import * as echarts from 'echarts';
import axios from 'axios';

export default {
  name: 'LineChart',
  data() {
    return {
      chartData: {
        months: [],
        counts: []
      }
    };
  },
  mounted() {
    this.initChart();
    this.fetchData();
  },
  methods: {
    initChart() {
      this.myChart = echarts.init(document.getElementById('item-zx'));
      this.option = {
        title: {
          text: '-- 12个月内空气质量超标趋势 --',
          left: 'center',
          textStyle: {
            color: '#E4FFFF' // 设置标题文字颜色为白色
          }
        },
        xAxis: {
          type: 'category',
          data: [],
          axisLabel: {
            color: '#fff' // 设置x轴文字颜色为白色
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            color: '#fff' // 设置y轴文字颜色为白色
          }
        },
        tooltip: {
          trigger: 'item',
          textStyle: {
            color: '#333' // 设置提示框文字颜色为原样（黑色）
          }
        },
        series: [
          {
            data: [],
            type: 'line',
            smooth: true
          }
        ]
      };
      this.myChart.setOption(this.option);
    },
    async fetchData() {
      try {
        let res = await axios.get('http://localhost:7000/service-nepm/administrator/getMonthCount');
        let result = res.data;
        console.log(result);

        // 初始化数据结构
        let months = [];
        let counts = [];

        // 根据后端数据进行填充
        result.forEach(item => {
          months.push(item.month);
          counts.push(item.level_over_count);
        });

        // 更新图表数据
        this.chartData = { months, counts };
        this.updateChart();
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    },
    updateChart() {
      this.option.xAxis.data = this.chartData.months;
      this.option.series[0].data = this.chartData.counts;
      this.myChart.setOption(this.option);
    }
  },
  beforeDestroy() {
    if (this.myChart) {
      this.myChart.dispose();
    }
  }
};
</script>

<style scoped>
#item-zx {
  width: 100%;
  height: 100%;
}
</style>
